package net.lab1024.sa.gateway.filter;

import net.lab1024.sa.gateway.config.TrafficDyeConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 流量染色过滤器
 */
@Order(-1) // 在设备指纹之后，路由之前执行
@Configuration
public class TrafficDyeFilter implements GlobalFilter {

    @Autowired
    private TrafficDyeConfig trafficDyeConfig;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 使用配置参数
        boolean enabled = trafficDyeConfig.isEnabled();
        if (!enabled) {
            return chain.filter(exchange);
        }

        String dyeKey = trafficDyeConfig.getDyeKey();
        // 从请求参数获取用户类型（如VIP用户）
        String userType = exchange.getRequest().getQueryParams().getFirst("userType");
        String tag = "normal";
        if ("vip".equals(userType)) {
            tag = "gray"; // VIP用户染色为"gray"
        } else if ("test".equals(userType)) {
            tag = "test"; // 测试用户染色为"test"
        }
        // 注入染色标签到请求头
        exchange.getRequest().mutate().header(dyeKey, tag).build();
        return chain.filter(exchange);
    }

}